package cn.edu.xust.AutoJwtFilter;

import cn.edu.xust.AuthJwt.JWTToken;
import cn.edu.xust.util.R;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@Slf4j
public class JWTFilter extends AuthenticatingFilter {


    /**
     * 创建一个token
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.info("jwtFilter-createToken");
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String token=request.getHeader("Authorization");
        if(StringUtils.isEmpty(token)) {
            return null;
        }
        return new JWTToken(token);
    }


    /**
     *
     * @param servletRequest
     * @param servletResponse
     * @return
     * @throws Exception
     */
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        log.info("jwtFilter-ServletRequest");
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        String token=request.getHeader("Authorization");
        if(!StringUtils.isEmpty(token)) {
            log.info("token不为空=>"+token);
            try {
                executeLogin(servletRequest, servletResponse);
                return true;
            }catch (Exception e){
                responseError(servletResponse,e.getMessage());
                return false;
            }
        }else {
            log.info("token为空");
            String uri = request.getRequestURI();
            if(uri.contains("login")){
                return true;
            }
            else{
                //如果不是login 需要登录
                try {
                    executeLogin(servletRequest, servletResponse);
                    return true;
                }catch (Exception e){
                    responseError(servletResponse,e.getMessage());
                    return false;
                }
            }
        }
    }

    /**
     * executeLogin实际上就是先调用createToken来获取token，这里我们重写了这个方法，
     * 就不会自动去调用createToken来获取token
     * 然后调用getSubject方法来获取当前用户再调用login方法来实现登录
     * 这也解释了我们为什么要自定义jwtToken，因为我们不再使用Shiro默认的UsernamePasswordToken了。
     */
    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        log.info("executeLogin");
        HttpServletRequest req= (HttpServletRequest) request;
        String token=req.getHeader("Authorization");
        JWTToken jwt=new JWTToken(token);
        //交给自定义的realm对象去登录，如果错误他会抛出异常并被捕获
        getSubject(request, response).login(jwt);
        return true;
    }

    /**
     * 前置处理器
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        log.info("jwtFilter-preHandle");

        HttpServletRequest req= (HttpServletRequest) request;
        HttpServletResponse res= (HttpServletResponse) response;

        res.setHeader("Access-control-Allow-Origin",res.getHeader("Origin"));
        res.setHeader("Access-control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
        res.setHeader("Access-Control-Allow-Headers", res.getHeader("Access-Control-Request-Headers"));
        if (req.getMethod().equals(RequestMethod.OPTIONS.name())){
            res.setStatus(org.springframework.http.HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 将非法请求跳转到 /unauthorized/**
     */
    private void responseError(ServletResponse response, String message) {
        log.info("responseError");

        try {
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //设置编码，否则中文字符在重定向时会变为空字符串
            message = URLEncoder.encode(message, "UTF-8");
//            httpServletResponse.sendRedirect("/unauthorized/" + message);
            log.info(message);
            response.setCharacterEncoding("UTF-8");

            httpServletResponse.getWriter().write(JSONObject.toJSONString( R.error(403,"认证过期，请重新登陆")));
        } catch (IOException e) {
            log.info(e.getMessage());
        }
    }
}
